package com.zhangpan.realtime.common.util;

import com.zhangpan.realtime.common.bean.TableProcessDim;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.flink.shaded.guava30.com.google.common.base.CaseFormat;

import javax.xml.transform.Result;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.zhangpan.realtime.common.constant.Constant.*;

public class JdbcUtil {

    public static Connection getMysqlConnection() throws SQLException, ClassNotFoundException {
        // 获取jdbc 链接
        //1. 加载驱动
        Class.forName(MYSQL_DRIVER);
        return DriverManager.getConnection(MYSQL_URL,MYSQL_USER_NAME,MYSQL_PASSWORD);

    }

    public static <T> List<T> queryList(Connection conn,String querySql,Class<T> tClass,
                                        boolean... isUnderlineToCamel) throws InvocationTargetException, IllegalAccessException, SQLException, InstantiationException {
        boolean defaultUToC = false;
        if (isUnderlineToCamel.length > 0) {
            defaultUToC = isUnderlineToCamel[0];
        }
        List<T> result = new ArrayList<>();
        //1. 预编译
        PreparedStatement preparedStatement = conn.prepareStatement(querySql);
        //2. 执行查询获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        //3. 解析结果集 把数据封装到一个List集合中
        while (resultSet.next()) {
            // 变量到一行数据 把这个行数据封装到一个T 类型的对象中
            T t = tClass.newInstance();
            // 便利这一行的每一列数据
            for (int i = 1;i<metaData.getColumnCount();i++) {
                // 获取列名
                // 获取列值
                String name = metaData.getColumnLabel(i);
                Object value = resultSet.getObject(name);
                if (defaultUToC) {
                    name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,name);
                }

                // t.name = value
                BeanUtils.setProperty(t,name,value);
                result.add(t);
            }

        }
        return result;
    }

    public static void closeConnection(Connection conn) throws SQLException {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {

        Connection conn = getMysqlConnection();

        List<TableProcessDim> list = queryList(conn,"select * from gmall2025_config.table_process_dim",TableProcessDim.class,true);


        for (Object obj:list) {

            System.out.println(obj);
        }

    }
}
